package com.yunc.modules.chat.controller;

import cn.hutool.core.date.DateUtil;
import com.yunc.common.utils.ShiroUtils;
import com.yunc.modules.sys.entity.SysUser;
import com.yunc.modules.sys.service.ISysUserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yunc.base.controller.CommonController;
import org.apache.commons.lang3.StringUtils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrSpliter;
import com.yunc.common.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunc.modules.chat.entity.ChatMessages;
import com.yunc.modules.chat.service.IChatMessagesService;

import java.util.List;

/**
 * 聊天记录表 前端控制器
 *
 * @author concong tao
 * @since 2019-03-28
 */
@RestController
@RequestMapping("/chat/messages")
public class ChatMessagesController extends CommonController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IChatMessagesService chatMessagesService;

    @GetMapping("/page")
    public R page(Page<ChatMessages> page, ChatMessages chatMessages){
        QueryWrapper<ChatMessages> qw = new QueryWrapper<>();
        Long userId = getUserId();
        qw.eq("type", "2");
        qw.and(wrapper -> wrapper.eq("from_user_id", userId).or().eq("to_user_id", userId));
        qw.orderByAsc("send_time");
        chatMessagesService.page(page, qw);
        List<ChatMessages> records = page.getRecords();
        // 获取其用户信息
        if (records != null && records.size() > 0) {
            for (ChatMessages message : records) {
                SysUser sysUser = sysUserService.getById(message.getFromUserId());
                SysUser toSysUser = sysUserService.getById(message.getToUserId());
                message.setUser(sysUser);
                message.setToUser(toSysUser);
            }
        }
        return R.ok().put("userId", userId).put("data", page.getRecords()).put("pages", page.getPages());
    }

    @GetMapping("/info/{id}")
    public R info(@PathVariable Long id){
        ChatMessages chatMessages = chatMessagesService.getById(id);
        return R.ok().put("chatMessages", chatMessages);
    }

    @PostMapping("/save")
    public R save(@RequestBody ChatMessages chatMessages){
        Long fromUserId = ShiroUtils.getUserId();
        ChatMessages record = chatMessagesService.getOne(new QueryWrapper<ChatMessages>()
                .eq("status", "1")
                .eq("from_user_id", fromUserId)
                .eq("to_user_id", chatMessages.getToUserId()));
        if (record != null) {
            return R.error("已发送过请求！");
        }
        ChatMessages recordt = chatMessagesService.getOne(new QueryWrapper<ChatMessages>()
                .eq("status", "1")
                .eq("from_user_id", chatMessages.getToUserId())
                .eq("to_user_id", fromUserId));
        if (recordt != null) {
            return R.error("对方已申请添加你为好友，请及时处理！");
        }

        chatMessages.setSendTime(DateUtil.date());
        chatMessages.setFromUserId(fromUserId);
        boolean flag = chatMessagesService.save(chatMessages);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    @PutMapping(value = "/update")
    public R update(@RequestBody ChatMessages chatMessages){
        boolean flag = chatMessagesService.updateById(chatMessages);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    @PutMapping(value = "/refuse/{fromUserId}")
    public R refuse(@PathVariable Long fromUserId){
        ChatMessages messages = chatMessagesService.getOne(new QueryWrapper<ChatMessages>()
                .eq("from_user_id", fromUserId)
                .eq("to_user_id", getUserId()));
        if (messages != null) {
            messages.setStatus("2");
            boolean flag = chatMessagesService.updateById(messages);
            if (flag) {
                return R.ok();
            }
        }
        return R.error();
    }

    @DeleteMapping("/delete/{ids}")
    public R delete(@PathVariable String ids){
        if (StringUtils.isEmpty(ids)) {
            return R.error("传入值为空");
        }
        List<String> idsList = StrSpliter.split(ids, ',', 0, true, true);
        if (CollUtil.isEmpty(idsList)) {
            return R.error("传入值格式错误");
        }
        boolean flag = chatMessagesService.removeByIds(idsList);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }
}
